/*
	addressbook functions
saved data format : 
	server1##{user1id=user1name||user2id=user2name}###server2##{user3id=user3name||user4id=user4name}	
*/

function createAddresBookContainer()	{
	
//	initRootElements();
	
//	overrideDefaultSenderButton();
	
	var addressBookDiv = document.createElement('div');
	addressBookDiv.id = 'addressBookDiv';	
	addressBookDiv.className = 'dynamic';
	addressBookDiv.style.display = 'block';	
	
	var headerObj = document.createElement('h3');
	headerObj.className = 'header';
	headerObj.innerHTML = getOtherTextInLang('ADDRESS_BOX_HEADER') + ' ' + getLanguageForDisplay() ;	
	addressBookDiv.appendChild( headerObj );

	addressBookList = getAddressBookList();	
	var addressBookTable = createAddressBookTable(addressBookList);	
	var addressBookTableDiv = document.createElement('div');
	addressBookTableDiv.id = 'addressBookTableDiv';
//	TODO Debug and fix sending ways	
//	TODO Message sending from island view
//	Commented due to unreliable multiple recipients sending, need time to debug	
//	addressBookTableDiv.style.display = userSettingValues['STARTING_DISPLAY_STATE_FOR_ADDRESS_BOOK'];	
	addressBookTableDiv.style.display = 'none';
	addressBookTableDiv.style.width = '95%';
	addressBookTableDiv.style.maxHeight = '200px';
	addressBookTableDiv.style.overflow = 'auto';
	
	addressBookTableDiv.appendChild( addressBookTable );
	addressBookDiv.appendChild( addressBookTableDiv );
	
//	Commented due to unreliable multiple recipients sending, need time to debug  	
//	addEvent( headerObj	, 'click', function(objId){openCloseObject( 'addressBookTableDiv' )}, true );
	
	addressBookDiv.appendChild( createAddUserTable() );	
	
	var footerDiv = document.createElement('div');
	footerDiv.className = 'footer';
	footerDiv.id = 'addressBookDivFooter';
	addressBookDiv.appendChild( footerDiv );
	
	return addressBookDiv;	
	
}

function createAddUserTable()	{
	var addUserTable = document.createElement('table');
	addUserTable.id = 'addUserTable';
	addUserTable.setAttribute('cellpadding', '0');
	addUserTable.setAttribute('cellspacing', '0');
	addUserTable.style.width = '90%';
	addUserTable.style.margin = 'auto';
	
	var addUserTableBody = document.createElement('tbody');
	
	var addUserTableHeader = document.createElement('th');
	addUserTableHeader.setAttribute('colspan', '2');
	addUserTableBody.appendChild( addUserTableHeader );
	
	addUserTableBody.appendChild( createPaddingRow(2, true) );
	
	var actualRow = document.createElement('tr');
	
	var actualCell = document.createElement('td');
	actualCell.appendChild(createInputElement('text', 'ADDUSER_INPUT', null, null));
	actualRow.appendChild( actualCell );	
	
	actualCell = document.createElement('td');
	var addUserIcon = createSubjectPicture(ADD_USER_TO_ADDRESSBOOK_ICON_PATH);
	addUserIcon.width = '25';
	addUserIcon.height = '25';
	actualCell.appendChild( addUserIcon );
	actualCell.valign = 'middle';
	actualCell.title = getOtherTextInLang('ADD_USER_TO_ADDRESSBOOK');
	addEvent( actualCell, 'click', function(objId){addUserToAddressBook( getNodeFirstChildByName( this.parentNode, 'INPUT', true ).value );}, true );			
	actualRow.appendChild( actualCell );	
	
	addUserTableBody.appendChild( actualRow );
	
	addUserTableBody.appendChild( createPaddingRow(2, true) );
	
	addUserTable.appendChild( addUserTableBody );	
	return addUserTable;
}

function createAddressBookTable(addressBookList)	{				
	
	var addressBookTable = document.createElement('table');
	addressBookTable.id = 'addressBookTable';
	addressBookTable.setAttribute('cellpadding', '0');
	addressBookTable.setAttribute('cellspacing', '0');
	addressBookTable.style.width = '90%';
	addressBookTable.style.margin = 'auto';
	
	var addressBookTableBody = document.createElement('tbody');
	addressBookTableBody.id = 'addressBookTableBody';
	
	var addressBookTableHeader = document.createElement('th');
	addressBookTableHeader.setAttribute('colspan', '3');	
	addressBookTableBody.appendChild( addressBookTableHeader );	
	
	if ( addressBookList != 'undefined' && addressBookList != null )	{			
		var addressBookArray = convertMapToArray( addressBookList );
		addressBookArray.sort( sortMultidimensionalArrayBySecondValInCaseSensitiveMode );	
		
		var adresse = null;	
		var actualRow = null;
		var i = 0;
		for ( i in addressBookArray )	{
			adresse = addressBookArray[i][0];
			addressBookTableBody.appendChild( createPaddingRow(3, true) );			
			
			actualRow = createRowWithAdresseInAddresBook(adresse);
			
			addressBookTableBody.appendChild( actualRow );					
		}		
		addressBookTableBody.appendChild( createPaddingRow(3, true) );			
	}
	
	addressBookTable.appendChild( addressBookTableBody );
	
	return addressBookTable;
}

function createRowWithAdresseInAddresBook(adresse)	{
	var actualRow = null;
	var actualCell =  null;
	
	actualRow = document.createElement('tr');
	actualCell = document.createElement('td');
	actualCell.id = 'USERID_' + adresse;
	actualCell.innerHTML = addressBookList[adresse];
	actualCell.title =  addressBookList[adresse];
	actualRow.appendChild( actualCell );
		
	var addAddresseButtonCell = createAddReceiverCell(adresse);
	addEvent( addAddresseButtonCell	, 'click', function(objId){appendAddresse( this.id.substring( 'ADD_RECEIVER_'.length ) );}, true );
	actualRow.appendChild( addAddresseButtonCell );
		
	var removeAddresseButtonCell = createRemoveReceiverCell(adresse);
	addEvent( removeAddresseButtonCell	, 'click', function(objId){removeAddresse( this.id.substring( 'REMOVE_RECEIVER_'.length ) );}, true );
	actualRow.appendChild( removeAddresseButtonCell );	
	
	return actualRow;
}

function addUserToAddressBook(userName)	{
	// check already exists 
	if ( containsValue(addressBookList, userName ) )	{
		return;
	}
	requestPlayerDetails(
		userName, 
		function(responseDetails){getUserIdFromRequest(responseDetails.responseText);}
	);
}

function getUserIdFromRequest(responseText)	{
	var hiddenDiv = document.createElement("div");
	hiddenDiv.innerHTML = responseText;

	var userDetailsTr = $X(".//div[@id='mainview']/div[@class='contentBox01h']/div[@class='content']/table[@class='table01']/tbody/tr/td[@class='name']/..", hiddenDiv );	
	if ( userDetailsTr == null )	{
		return;
	}
	
	var userMessageLink = $X("./td[@class='action']/a", userDetailsTr);
	var userNameTdFromResponse = $X("./td[@class='name']", userDetailsTr);
	
	if ( userMessageLink == null || userNameTdFromResponse == null )	{
		return;
	}
	
	var strStartWithUserId = userMessageLink.href.split('&with=')[1];
	var userIdFromResponse = strStartWithUserId.split('&')[0];
	
	if ( addressBookList[userIdFromResponse] != null )	{
		// or update values ?
		return;
	}
	
	var userNameFromResponse = userNameTdFromResponse.innerHTML;
	addressBookList[userIdFromResponse] = userNameFromResponse;
	
	var addressBookTableBody = $X(".//div[@id='addressBookTableDiv']/table[@id='addressBookTable']/tbody");
	var addressBookTableRows = $x("./tr/td[starts-with(@id,'USERID')]", addressBookTableBody );	

	if ( addressBookTableRows == null || addressBookTableRows.length == 0 )	{	// first user in ABC in this addressbook
		addressBookTableBody.appendChild( createRowWithAdresseInAddresBook(userIdFromResponse) );
		addressBookTableBody.appendChild( createPaddingRow(3, true) );
	}
	else	{
		var c = addressBookTableRows.length;
		var i = 0;
		
		var fuckingTempArrayToSortUserNames = new Array();
		fuckingTempArrayToSortUserNames.push( userNameFromResponse.toUpperCase() );
		
		for ( i = 0; i != c; i++ )	{
			fuckingTempArrayToSortUserNames.push( addressBookTableRows[i].title.toUpperCase() );
		}
		fuckingTempArrayToSortUserNames.sort();		
		
		i = 0;
		while ( i != c && fuckingTempArrayToSortUserNames[i] != userNameFromResponse.toUpperCase() )	{			
			i++;
		}		

		if ( i == c )	{	// new user will be the last in the addressbook
			addressBookTableBody.appendChild( createRowWithAdresseInAddresBook(userIdFromResponse) );
			addressBookTableBody.appendChild( createPaddingRow(3, true) );
		}
		else	{
			var insertAfter = addressBookTableRows[i].parentNode;
			insertAfter = addressBookTableBody.insertBefore(createRowWithAdresseInAddresBook(userIdFromResponse), insertAfter);
			if (insertAfter) {
            	insertAfter = insertAfter.nextSibling;
        	}
			addressBookTableBody.insertBefore(createPaddingRow(3, true), insertAfter);
		}	
	}
	
	saveAddressBookList( addressBookList );
}

function createAddReceiverCell(userid)	{
	var res = createButtonLikeCell( '+' );
	res.id = 'ADD_RECEIVER_' + userid;	
	res.title = getOtherTextInLang('ADD_USER_TO_RECIPIENTS') + addressBookList[userid];
	return res;
}

function createRemoveReceiverCell(userid)	{
	var res = createButtonLikeCell( 'X' );
	res.id = 'REMOVE_RECEIVER_' + userid;
	res.title = getOtherTextInLang('REMOVE_USER_FROM_RECIPIENTS') + addressBookList[userid];
	return res;
}

function appendAddresse(recipientId)	{	
	if ( recipientCount == NUMBER_OF_MAX_RECIPIENTS )	{
		window.alert( getOtherTextInLang( 'RECIPIENTS_ARE_TOO_MUCH' ) );
		return;
	}
	
	var existingRecipientWithThisId = $X("./input[@id="+recipientId+"]", hiddenDataDiv);
	if ( existingRecipientWithThisId != null )	{
		return;
	}
	
	var newHiddenRecipient = createInputElement('hidden', recipientId, addressBookList[recipientId], null);
	hiddenDataDiv.appendChild( newHiddenRecipient );	
	
	var newRecipientSpan = document.createElement('span');
	newRecipientSpan.id = addressBookList[recipientId];
	
	var spanText = addressBookList[recipientId];
	if ( recipientCount != 0 )	{
		// we have at least one recipients 
		spanText = ', ' + spanText;
	}
	
	newRecipientSpan.appendChild( document.createTextNode( spanText ) );
	addEvent( newRecipientSpan	, 'click', function(recipientName){removeAddresseByName( addressBookList[recipientId] );}, true );
	mailRecipientDiv.appendChild( newRecipientSpan );
	recipientCount++;	
	return;	
}

function removeAddresse(recipientId)	{		
	var recipientName = addressBookList[recipientId];	
	var removeElement = $X("./span[not(@class) and @id='" + recipientName + "']", mailRecipientDiv );
	var firstElement = $X("./span[not(@class)]", mailRecipientDiv );

	if ( firstElement == null || removeElement == null )	{		
		return;
	}
	
	recipientCount--;
	
	if ( removeElement.id == firstElement.id && recipientCount != 0 )	{
		var secondElement = $X("./span[not(@class) and @id!='" + recipientName + "']", mailRecipientDiv );
		secondElement.innerHTML = secondElement.innerHTML.replace(/,/, '');
	}
	
	removeElement.parentNode.removeChild ( removeElement );	
		
	var removeHiddenElement = $X("./input[@id='" + recipientId + "']", hiddenDataDiv );
	removeHiddenElement.parentNode.removeChild ( removeHiddenElement );
//	hiddenDataDiv.removeChild( removeHiddenElement );	
	return;	
}

function removeAddresseByName(recipientName)	{	
	recipientCount--;
	if ( recipientCount == 0 )	{
		recipientCount++;
		return;
	}	
	var removeHiddenElement = $X("./input[@value='" + recipientName + "']", hiddenDataDiv );
	removeHiddenElement.parentNode.removeChild ( removeHiddenElement );
	
	var removeElement = $X("./span[not(@class) and @id='" + recipientName + "']", mailRecipientDiv );
	
	var firstElement = $X("./span[not(@class)]", mailRecipientDiv );	
	if ( removeElement.id == firstElement.id && recipientCount != 0 )	{
		var secondElement = $X("./span[not(@class) and @id!='" + recipientName + "']", mailRecipientDiv );
		secondElement.innerHTML = secondElement.innerHTML.replace(/,/, '');
	}
	
	removeElement.parentNode.removeChild ( removeElement );
//	noticeDiv.removeChild ( removeElement );
	return;
}

function initRootElements()	{
	
	mailRecipientDiv = $X("./form/div[@id='mailRecipient']", noticeDiv );	
	hiddenDataDiv = $X("./form/div[@id='hiddenDataDiv']", noticeDiv );
	mailRecipients = $x("./span[not(@class)]", mailRecipientDiv );
	
	var receiver = $X("./form/input[@name='receiverId']", noticeDiv );
	var receiverName = $X("./form/input[@name='receiverName']", noticeDiv );
	
	if ( hiddenDataDiv == 'undefined' || hiddenDataDiv == null )	{
		hiddenDataDiv = createHiddenDiv('hiddenDataDiv', null);
		noticeDiv.appendChild( hiddenDataDiv );		
	}
	
	// Store the default recepient in my list
	var defaultRecipient = createInputElement('hidden', receiver.value, receiverName.value, null);
	hiddenDataDiv.appendChild( defaultRecipient );	
	
	var i = 0;	
	for ( i = 0; i != mailRecipients.length; i++ )	{
		receiverName = mailRecipients[i].innerHTML;
		mailRecipients[i].id = receiverName;		 
		addEvent( mailRecipients[i]	, 'click', function(recipientName){removeAddresseByName(receiverName);}, true );
	}	
}

function sendMyMessage()	{
	var myForm = $X(".//div[@id='mainview']/div[@id='notice']/form" );
	var myMailRecipients = $x("./input", hiddenDataDiv );
	
	if ( myMailRecipients.length == 1 )	{
		myForm.submit();
		return;
	}
	
	var hiddenMessageSenderDiv = createHiddenDiv('hiddenMessageSenderDiv', null );
	noticeDiv.parentNode.appendChild( hiddenMessageSenderDiv );
	
	var i = 0;
	for (i = 0; i != myMailRecipients.length; i++ )	{
		
		var hiddenMessageSenderFrame = document.createElement('iframe');
		hiddenMessageSenderFrame.setAttribute('src', 'index.php');
		var frameName = 'hiddenframe' + myMailRecipients[i].id;
		
		hiddenMessageSenderFrame.setAttribute('name', frameName );
		hiddenMessageSenderFrame.setAttribute('WIDTH', 1  );
		hiddenMessageSenderFrame.setAttribute('HEIGHT', 1  );
		hiddenMessageSenderFrame.setAttribute('frameborder', 0 );				
		hiddenMessageSenderFrame.setAttribute('border', 0 );		
		
		hiddenMessageSenderDiv.appendChild( hiddenMessageSenderFrame );		
		var receiverIdElement = $X("./input[@name='receiver']", myForm );
		var receiverNameElement = $X("./input[@name='receiverName']", myForm );		
		receiverIdElement.value = myMailRecipients[i].id;
		receiverNameElement.value = myMailRecipients[i].value;
		
//		GM_log ( 'recipient : ' + myMailRecipients[i].id + ' - ' + myMailRecipients[i].value );
		
		myForm.target = frameName;
		myForm.submit();		
	}
	history.back();
}

function sendAllyMessage()	{		
	noticeDiv = $X(".//div[@id='mainview']/div[@id='notice']");
	var myForm = $X("./form", noticeDiv );
	
	var myFormInputElements = $x("./input", myForm);
	var i = 0;
	for ( i = 0; i != myFormInputElements.length; i++ )	{
		if ( myFormInputElements[i].name == 'receiverId')	{
			myForm.removeChild( myFormInputElements[i] );
			break;
		}
	}
	
	var mySpanElement = $X("./div[@id='mailSubject']/span[string-length(@class)=0]", myForm);
	mySpanElement.removeChild( mySpanElement.firstChild );

	mySpanElement.appendChild (createInputElementWithName('hidden', null, 0, null, 'relType' ) );
	mySpanElement.appendChild (createInputElementWithName('hidden', null, 0, null, 'relAction' ) );
	mySpanElement.appendChild (createInputElementWithName('hidden', null, 0, null, 'relCity' ) );
	mySpanElement.appendChild (createInputElementWithName('hidden', 'treaties', 51, null, 'msgType' ) );
	var allyDetails = GM_getValue( 'PLAYER_ALLY_DETAILS' );
	var allyId = parseInt(allyDetails.split('=')[0]);
	mySpanElement.appendChild (createInputElementWithName('hidden', null, allyId, null, 'allyId' ) );
	/*
	mySpanElement.appendChild (createInputElementWithName('hidden', null, 3233, null, 'allyId' ) );	
	GM_log ( 'mySpanElement: ' + mySpanElement.innerHTML );
	// SPQRa
	*/
	
	myForm.submit();	
}

